<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-box">
        <!-- 顶部欢迎信息 -->
        <div class="welcome-header">
          <h1>欢迎回来</h1>
          <p>使用多种身份验证方法进行安全登录</p>
        </div>

        <!-- 登录方式选择标签 -->
        <div class="login-tabs">
          <div 
            class="tab-item" 
            :class="{ active: loginMode === 'password' }"
            @click="switchLoginMode('password')"
            @mouseenter="logger.log('鼠标进入密码标签')"
            tabindex="0"
          >
            🔒密码
          </div>

          <div 
            class="tab-item" 
            :class="{ active: loginMode === 'email' }"
            @click="switchLoginMode('email')"
            @mouseenter="logger.log('鼠标进入邮件标签')"
            tabindex="0"
          >
            📧电子邮件
          </div>
        </div>

        <!-- 密码登录表单 -->
        <div class="login-form" v-if="loginMode === 'password'">
          <div class="form-group" :class="{ 'has-error': usernameError }">
            <input 
              type="text" 
              placeholder="账号" 
              v-model="username" 
              class="form-control"
              @blur="validateUsername"
              @input="validateUsername"
            >
            <div class="error-message" v-if="usernameError">{{ usernameError }}</div>
          </div>
          <div class="form-group" :class="{ 'has-error': passwordError }">
            <div class="password-input-container">
              <input 
                :type="showPassword ? 'text' : 'password'" 
                placeholder="密码" 
                v-model="password" 
                class="form-control"
                @blur="validatePassword"
              >
              <span 
                class="password-toggle" 
                @click="togglePasswordVisibility"
              >
                {{ showPassword ? '👁️' : '👁️‍🗨️' }}
              </span>
            </div>
            <div class="error-message" v-if="passwordError">{{ passwordError }}</div>
          </div>
          


          <div class="button-group">
            <button 
              class="login-btn" 
              @click="handleAccountLogin" 
              :disabled="isLoading"
              type="button"
            >
              <span v-if="isLoading" class="loading-spinner"></span>
              <span v-else>登录</span>
            </button>
          </div>
        </div>



        <!-- 邮箱验证码登录表单 -->
        <div class="login-form" v-if="loginMode === 'email'">
          <div class="form-group" :class="{ 'has-error': usernameError }">
            <input 
              type="email" 
              placeholder="电子邮件地址" 
              v-model="username" 
              class="form-control"
              @blur="validateUsername"
              @input="validateUsername"
            >
            <div class="error-message" v-if="usernameError">{{ usernameError }}</div>
            <div class="hint-message">输入正确邮箱才能点击获取验证码</div>
          </div>
          
          <div class="form-group verification-group">
            <input 
              type="text" 
              placeholder="请输入邮箱验证码" 
              v-model="emailVerificationCode" 
              class="form-control verification-control" 
              @blur="validateEmailVerificationCode" 
              maxlength="10"
            >
            <button class="verification-btn" @click="showCaptchaModal" :disabled="!isEmailValid">获取验证码</button>
          </div>
          <div class="error-message" v-if="emailVerificationCodeError">{{ emailVerificationCodeError }}</div>

          <div class="button-group">
            <button 
              class="login-btn" 
              @click="handleEmailLogin" 
              :disabled="isLoading"
              type="button"
            >
              <span v-if="isLoading" class="loading-spinner"></span>
              <span v-else>验证并登录</span>
            </button>
          </div>
        </div>

        <div class="divider">
          <span>其他登录方式</span>
        </div>

        <div class="login-options">
          <button class="guest-login-btn" @click="guestLogin">游客访问</button>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 图形验证码弹窗 -->
  <div class="captcha-modal" v-if="captchaModalVisible">
    <div class="captcha-container">
      <div class="captcha-header">
        <h3>请完成验证</h3>
        <span class="close-btn" @click="closeCaptchaModal">&times;</span>
      </div>
      <div class="captcha-content">
        <div class="captcha-image-container">
          <img :src="captchaImage" alt="验证码" class="captcha-image" v-if="captchaImage" @error="onImageError" @load="onImageLoad">
          <div class="captcha-loading" v-else>加载中...</div>
        </div>
        <div class="captcha-input-group">
          <input type="text" placeholder="请输入验证码" v-model="captchaCode" class="captcha-input">
        </div>
      </div>
      <div class="captcha-footer">
        <button class="captcha-refresh-btn" @click="refreshCaptcha">
          <i class="refresh-icon">↻</i> 换一张
        </button>
        <button class="captcha-confirm-btn" @click="verifyCaptcha">确认</button>
      </div>
    </div>
  </div>
  
      <!-- 邮箱验证码发送状态提示 -->
    <div class="email-sending-modal" v-if="isSendingEmail">
      <div class="email-sending-container">
        <div class="email-sending-content">
          <div class="loading-spinner-large"></div>
          <h3>正在发送邮箱验证码...</h3>
          <p>请稍候，验证码将发送到 {{ username }}</p>
          <p v-if="emailSendRetryCount > 0" class="retry-info">正在重试 (第{{ emailSendRetryCount }}次)</p>
        </div>
      </div>
    </div>


</template>

<script>
import { userApi } from '@/api'
import logger from '../utils/logger.js'

export default {
  name: 'LoginView',
  data() {
    return {
      loginMode: 'password', // 'password', 'email'
      username: '',
      password: '',
      showPassword: false,
      usernameError: '',
      passwordError: '',
      isLoading: false,
      logger: logger, // 暴露logger给模板使用
      emailVerificationCode: '',
      emailVerificationCodeError: '',
      captchaModalVisible: false,
      captchaImage: '',
      captchaCode: '',
      captchaId: null,
      isSendingEmail: false,
      emailSendRetryCount: 0,
      hasToken: false // 是否有JWT令牌
    };
  },
  computed: {
    isEmailValid() {
      if (!this.username) return false;
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return emailRegex.test(this.username);
    }
  },
  methods: {
      // 安全检查localStorage中的token
      checkTokenStatus() {
        try {
          if (typeof window !== 'undefined' && window.localStorage) {
            this.hasToken = !!localStorage.getItem('token');
          } else {
            this.hasToken = false;
          }
        } catch (error) {
          logger.warn('⚠️ localStorage访问失败:', error);
          this.hasToken = false;
        }
      },
    // 切换登录方式
    switchLoginMode(mode) {
      logger.log('🔄 切换登录方式到:', mode);
      this.loginMode = mode;
      this.clearErrors();
      logger.log('✅ 当前登录模式:', this.loginMode);
    },
    
    // 清除所有错误信息
    clearErrors() {
      this.usernameError = '';
      this.passwordError = '';
      this.emailVerificationCodeError = '';
    },
    
    // 触发用户信息更新事件
    triggerUserInfoUpdate(userInfo) {
      try {
        const event = new CustomEvent('userInfoUpdated', { detail: userInfo });
        window.dispatchEvent(event);
        logger.log('📢 已触发用户信息更新事件');
      } catch (error) {
        logger.warn('⚠️ 触发用户信息更新事件失败:', error);
      }
    },

    // 账号密码登录
    async handleAccountLogin() {
      logger.log('🔥 账号密码登录按钮被点击！');
      
      this.validateUsername();
      this.validatePassword();
      
      if (this.usernameError || this.passwordError) {
        return;
      }
      
      this.isLoading = true;
      
      try {
        const loginData = {
          account: this.username,
          password: this.password
        };
        
        logger.log('🚀 发送账号密码登录请求...');
        logger.log('📋 登录数据:', loginData);
        logger.log('🌐 当前环境:', process.env.NODE_ENV);
        logger.log('🔗 API baseURL:', '/api');
        
        const response = await userApi.accountLogin(loginData);
        
        logger.log('📥 收到响应:', response);
        logger.log('📥 响应类型:', typeof response);
        logger.log('📥 响应结构:', JSON.stringify(response, null, 2));
        
        if (response && (response.code === 0 || response.status === 'success')) {
          // 登录成功，处理用户信息
          // 使用与邮箱验证码登录相同的token提取逻辑
          let token;
          
          // 检查response.data是否是字符串格式的JWT令牌
          if (typeof response?.data === 'string' && response.data.startsWith('eyJ')) {
            logger.log('🔑 在response.data中找到JWT令牌:', response.data);
            token = response.data;
          } else if (response?.token && typeof response.token === 'string') {
            logger.log('🔑 使用response.token中的JWT令牌:', response.token);
            token = response.token;
          } else if (response?.data?.token && typeof response.data.token === 'string') {
            logger.log('🔑 使用response.data.token中的JWT令牌:', response.data.token);
            token = response.data.token;
          } else {
            logger.log('⚠️ 邮箱密码登录：后端未返回JWT令牌，生成临时token');
            logger.log('⚠️ 响应结构分析:', {
              'response.token': response?.token,
              'response.data.token': response?.data?.token,
              'response.data': response?.data,
              'response.data类型': typeof response?.data
            });
            // 如果后端没有返回JWT令牌，生成临时token
            token = 'account_login_token_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            logger.log('🔑 生成临时token:', token);
          }
          
          const userInfo = {
            username: this.username.split('@')[0] || this.username,
            email: this.username.includes('@') ? this.username : '',
            account: this.username,
            avatar: '',
            id: Date.now(),
            role: 'user',
            nickname: this.username.split('@')[0] || this.username,
            loginTime: new Date().toISOString(),
            loginMethod: 'account'
          };
          
          localStorage.setItem('userInfo', JSON.stringify(userInfo));
          localStorage.setItem('token', token);
          
          this.completeLogin(userInfo, token);
        } else {
          alert('登录失败：' + (response?.message || '账号或密码错误'));
        }
        
      } catch (error) {
        logger.error('账号密码登录失败:', error);
        if (error.response?.status === 401) {
          alert('账号或密码错误，请重新输入');
        } else if (error.response?.data?.message) {
          alert('登录失败：' + error.response.data.message);
        } else {
          alert('登录失败，请稍后重试');
        }
      } finally {
        this.isLoading = false;
      }
    },



    // 邮箱验证码登录（原有逻辑）
    async handleEmailLogin() {
      logger.log('🔥 邮箱验证码登录按钮被点击！');
      this.login();
    },




    
    // 处理登录按钮点击事件
    handleLogin() {
      logger.log('🎯 登录按钮被点击');
      this.login();
    },
    
    validateUsername() {
      if (!this.username) {
        this.usernameError = this.loginMode === 'email' ? '请输入邮箱' : '请输入账号';
      } else if (this.loginMode === 'email') {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(this.username)) {
          this.usernameError = '请输入有效的邮箱地址';
        } else {
          this.usernameError = '';
        }
      } else {
        this.usernameError = '';
      }
    },
    validatePassword() {
      // 在邮箱登录模式下，不需要密码
      if (this.loginMode === 'email') {
        this.passwordError = '';
        return;
      }
      
      if (!this.password) {
        this.passwordError = '请输入密码';
      } else if (this.password.length < 6) {
        this.passwordError = '密码长度不能少于6个字符';
      } else {
        this.passwordError = '';
      }
    },
    validateEmailVerificationCode() {
      if (!this.emailVerificationCode) {
        this.emailVerificationCodeError = '请输入邮箱验证码';
      } else {
        this.emailVerificationCodeError = '';
      }
    },
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
    async login() {
      logger.log('🔥 登录按钮被点击了！');
      logger.log('当前邮箱:', this.username);
      logger.log('当前密码:', this.password);
      logger.log('isLoading状态:', this.isLoading);
      
      // 根据登录模式验证不同的表单字段
      this.validateUsername();
      
      if (this.loginMode === 'password') {
        // 账号密码登录模式
        this.validatePassword();
        if (this.usernameError || this.passwordError) {
          return;
        }
      } else if (this.loginMode === 'email') {
        // 邮箱验证码登录模式
        this.validateEmailVerificationCode();
        if (this.usernameError || this.emailVerificationCodeError) {
          return;
        }
      }
      
      this.isLoading = true;
      
      try {
        // 根据登录模式构建不同的请求数据
        let loginData;
        
        if (this.loginMode === 'email') {
          // 邮箱验证码登录 - 只发送邮箱和验证码
          loginData = {
            account: this.username,               // 邮箱
            code: this.emailVerificationCode      // 邮箱验证码
          };
          logger.log('📧 邮箱验证码登录模式，发送数据:', loginData);
        } else {
          // 账号密码登录模式
          loginData = {
            account: this.username,               // 账号
            password: this.password               // 密码
          };
          logger.log('🔐 账号密码登录模式，发送数据:', loginData);
        }
        
        logger.log('🚀 发送登录验证请求到后端...');
        const response = await userApi.login(loginData);
        logger.log('📥 后端验证结果:', response);
        logger.log('🔍 登录响应详情:', response);
        logger.log('🔍 响应类型:', typeof response);
        logger.log('🔍 响应结构:', JSON.stringify(response, null, 2));
        
        // 详细分析响应结构
        if (response) {
          logger.log('🔍 响应字段分析:');
          logger.log('  - response.code:', response.code);
          logger.log('  - response.message:', response.message);
          logger.log('  - response.data:', response.data);
          logger.log('  - response.token:', response.token);
          logger.log('  - response.user:', response.user);
          logger.log('  - response.userInfo:', response.userInfo);
          
          if (response.data) {
            logger.log('🔍 data字段详情:');
            logger.log('  - response.data.token:', response.data.token);
            logger.log('  - response.data.user:', response.data.user);
            logger.log('  - response.data.userInfo:', response.data.userInfo);
          }
        }
        
        // 检查各种成功标识
        const hasToken = !!(response?.token || response?.data?.token);
        const isSuccessCode = response?.code === 0 || response?.code === 200 || response?.status === 'success';
        const hasMessage = response?.message;
        
        logger.log('🔍 成功标识检查:');
        logger.log('  - hasToken:', hasToken);
        logger.log('  - isSuccessCode:', isSuccessCode);
        logger.log('  - hasMessage:', hasMessage);
        logger.log('  - response.code:', response?.code);
        logger.log('  - response.status:', response?.status);
        
        // 简化的登录成功判断：后端只返回成功/失败状态，不返回用户数据
        const shouldTreatAsSuccess = (response?.code === 0) || 
                                   (response?.status === 'success') ||
                                   (response?.message === '登录成功') ||
                                   (response && !response.error && response.code !== 1 && !response.message?.includes('错误'));
        
        // 检查是否有明确的错误标识
        const hasError = response?.code === 1 || 
                        response?.error || 
                        (response?.message && (
                          response.message.includes('错误') || 
                          response.message.includes('失败') ||
                          response.message.includes('denied') ||
                          response.message.includes('invalid') ||
                          response.message.includes('不正确') ||
                          response.message.includes('不存在')
                        ));
        
        logger.log('🎯 是否应该视为成功:', shouldTreatAsSuccess);
        logger.log('🎯 是否有错误标识:', hasError);
        
        if (shouldTreatAsSuccess && !hasError) {
          logger.log('✅ 后端验证登录成功，开始处理用户信息...');
          
          // 获取后端返回的JWT令牌
          // 根据控制台信息，JWT令牌在response.data字段中
          const jwtToken = response?.token || response?.data?.token || response?.data;
          let token;
          
          // 检查response.data是否是字符串格式的JWT令牌
          if (typeof response?.data === 'string' && response.data.startsWith('eyJ')) {
            logger.log('🔑 在response.data中找到JWT令牌:', response.data);
            token = response.data;
          } else if (jwtToken && typeof jwtToken === 'string') {
            logger.log('🔑 使用后端返回的JWT令牌:', jwtToken);
            token = jwtToken;
          } else {
            logger.log('⚠️ 后端未返回JWT令牌，生成临时token');
            logger.log('⚠️ 响应结构分析:', {
              'response.token': response?.token,
              'response.data.token': response?.data?.token,
              'response.data': response?.data,
              'response.data类型': typeof response?.data
            });
            // 如果后端没有返回JWT令牌，生成临时token
            token = 'login_token_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            logger.log('🔑 生成临时token:', token);
          }
          
          // 获取注册时保存的用户信息
          const userProfileStr = localStorage.getItem('userProfile');
          let userInfo = null;
          
          if (userProfileStr) {
            try {
              const savedProfile = JSON.parse(userProfileStr);
              logger.log('📋 找到保存的用户资料:', savedProfile);
              
              // 验证邮箱是否匹配（确保是同一个用户）
              if (savedProfile.email === this.username || savedProfile.account === this.username) {
                userInfo = {
                  ...savedProfile,
                  loginTime: new Date().toISOString(),
                  _lastLogin: new Date().toISOString()
                };
                logger.log('✅ 邮箱匹配，使用保存的用户信息');
              } else {
                logger.log('⚠️ 邮箱不匹配，创建新的用户信息');
              }
            } catch (error) {
              logger.error('解析用户资料失败:', error);
            }
          }
          
          // 如果没有找到匹配的用户信息，创建一个基础的
          if (!userInfo) {
            logger.log('📝 创建新的用户信息...');
            userInfo = {
              username: this.username.split('@')[0],
              email: this.username,
              account: this.username,
              avatar: '',
              id: Date.now(),
              role: 'user',
              nickname: this.username.split('@')[0],
              loginTime: new Date().toISOString(),
              registerTime: null,
              _source: 'login_created'
            };
          }
          
          logger.log('🔍 最终用户信息:', userInfo);
          
          // 保存用户信息和token
          localStorage.setItem('userInfo', JSON.stringify(userInfo));
          localStorage.setItem('token', token);
          
          this.completeLogin(userInfo, token);
        } else if (response && response.code === 1) {
          // 处理登录失败的情况
          logger.log('❌ 登录失败，错误信息:', response.message);
          alert('❌ 登录失败：' + (response.message || '请检查账号密码'));
          
          // 在页面上也显示错误信息
          if (response.message && response.message.includes('密码')) {
            this.passwordError = response.message;
          } else if (response.message && (response.message.includes('账号') || response.message.includes('邮箱'))) {
            this.usernameError = response.message;
          } else if (response.message && response.message.includes('验证码')) {
            this.emailVerificationCodeError = response.message;
          } else {
            this.passwordError = response.message || '登录失败，请检查邮箱密码';
          }
        } else {
          // 登录失败处理
          logger.log('❌ 登录失败，无法确认身份验证');
          logger.log('🔧 失败响应:', response);
          
          // 显示错误信息
          const errorMessage = response?.message || response?.msg || '登录失败，请检查账号密码';
          alert('❌ ' + errorMessage);
          
          // 在表单上显示错误
          if (errorMessage.includes('密码')) {
            this.passwordError = errorMessage;
          } else if (errorMessage.includes('账号') || errorMessage.includes('邮箱')) {
            this.usernameError = errorMessage;
          } else if (errorMessage.includes('验证码')) {
            this.emailVerificationCodeError = errorMessage;
          } else {
            this.passwordError = errorMessage;
          }
        }
        
      } catch (error) {
        logger.error('登录失败:', error);
        
        // 根据错误类型提供不同的提示
        if (error.response) {
          const status = error.response.status;
          const data = error.response.data;
          
          if (status === 401) {
            alert('邮箱或密码错误，请重新输入');
          } else if (status === 403) {
            alert('账号已被锁定，请联系管理员');
          } else if (data && data.message) {
            alert(data.message);
          } else {
            alert('登录失败，请稍后重试');
          }
        } else if (error.request) {
          alert('网络连接失败，请检查网络设置');
        } else {
          alert('登录请求失败，请稍后重试');
        }
      } finally {
        this.isLoading = false;
      }
    },
    
    // 完成登录流程
    completeLogin(userInfo, token) {
      // 清除临时数据
      localStorage.removeItem('loginHint');
      
      logger.log('✅ 用户信息已保存:', userInfo);
      logger.log('✅ Token已保存:', token);
      logger.log('✅ 临时数据已清除');
      logger.log('✅ localStorage内容:');
      logger.log('  - userInfo:', localStorage.getItem('userInfo'));
      logger.log('  - token:', localStorage.getItem('token'));
      
      // 触发用户信息更新事件，通知其他组件
      this.triggerUserInfoUpdate(userInfo);
      
      alert('登录成功！即将跳转到首页...');
      logger.log('✅ 登录成功，准备跳转到首页');
      
      // 延迟跳转，确保数据保存完毕
      setTimeout(() => {
        logger.log('🚀 正在跳转到首页...');
        this.$router.push('/');
      }, 100);
    },
    


    


    

    

    

    

    


    
    guestLogin() {
      alert('游客访问中...');
      this.$router.push('/');
    },
         // 新增：显示图形验证码弹窗
     showCaptchaModal() {
       if (!this.isEmailValid) {
         alert('请先输入有效的邮箱地址');
         return;
       }
       this.captchaModalVisible = true;
       this.loadCaptcha();
     },
     // 新增：关闭图形验证码弹窗
     closeCaptchaModal() {
       this.captchaModalVisible = false;
       this.captchaCode = '';
     },
     // 新增：隐藏验证码弹窗（不清空验证码）
     hideCaptchaModal() {
       this.captchaModalVisible = false;
     },
     // 新增：加载图形验证码
     async loadCaptcha() {
       try {
         logger.log('🔄 开始加载验证码...');
         const response = await userApi.getCaptcha();
         logger.log('📨 验证码API响应:', response);
         
         // 处理base64验证码图片
         let imageData = null;
         let captchaId = null;
         
         if (response && typeof response === 'object') {
           // 处理后端返回的数据格式
           if (response.captcha && response.captchaUuid) {
             imageData = response.captcha;
             captchaId = response.captchaUuid;
           } else if (response.img) {
             imageData = response.img;
             captchaId = response.uuid || response.id || response.captchaId;
           } else if (response.data) {
             imageData = response.data.captcha || response.data.img;
             captchaId = response.data.captchaUuid || response.data.uuid || response.data.id;
           }
         }
         
         if (imageData) {
           // 处理base64图片，转换为PNG显示
           this.captchaImage = this.processBase64Image(imageData);
           this.captchaId = captchaId || Date.now().toString();
           logger.log('✅ 验证码加载成功!');
         } else {
           throw new Error('未找到验证码图片数据');
         }
       } catch (error) {
         logger.error('❌ 验证码加载失败:', error);
         alert('验证码加载失败，请重试');
         this.closeCaptchaModal();
       }
     },
     // 新增：刷新图形验证码
     refreshCaptcha() {
       this.loadCaptcha();
     },
     // 新增：处理base64图片
     processBase64Image(data) {
       if (!data) return '';
       
       // 如果已经是完整的data URI
       if (data.startsWith('data:image/')) {
         return data;
       }
       
       // 如果是HTTP/HTTPS URL
       if (data.startsWith('http')) {
         return data;
       }
       
       // 处理纯base64字符串，转换为PNG
       const cleanBase64 = data.replace(/[\s\n\r\t]/g, '');
       return `data:image/png;base64,${cleanBase64}`;
     },
         // 新增：验证图形验证码
     async verifyCaptcha() {
       if (!this.captchaCode) {
         alert('请输入验证码');
         return;
       }
       
       if (!this.captchaId) {
         alert('验证码ID丢失，请重新获取验证码');
         this.refreshCaptcha();
         return;
       }
       
       try {
         logger.log('🔐 开始验证图形验证码并发送邮箱验证码...');
         logger.log('🔐 当前图形验证码:', this.captchaCode);
         logger.log('🆔 当前验证码ID:', this.captchaId);
         logger.log('📧 目标邮箱:', this.username);
         
         // 构建发送邮件验证码的请求数据（同时验证图形验证码）
         const emailCodeData = {
           toEmail: this.username,
           captcha: this.captchaCode,
           captchaUuid: this.captchaId
         };
         
         logger.log('📧 发送邮件验证码数据:', emailCodeData);
         
         // 调用发送邮件验证码接口（同时验证图形验证码）
         const response = await userApi.sendEmailCode(emailCodeData);
         
         logger.log('✅ 邮件验证码发送成功！', response);
         
         // 验证成功后隐藏弹窗
         this.hideCaptchaModal();
         
         // 显示成功消息
         alert('验证码已发送到您的邮箱，请查收！');
         
       } catch (error) {
         logger.error('❌ 发送邮件验证码失败:', error);
         
         // 处理不同类型的错误
         if (error.message) {
           alert(error.message);
         } else if (error.response && error.response.status === 400) {
           alert('验证码错误，请重新输入');
         } else if (error.response && error.response.status === 404) {
           alert('验证码已过期，请重新获取');
           this.refreshCaptcha();
         } else {
           alert('发送验证码失败，请重试');
         }
         
         this.captchaCode = '';
       }
     },
     // 新增：发送邮箱验证码
     async sendEmailVerificationCode() {
       // 再次确认邮箱地址是否有效
       if (!this.username) {
         alert('请先填写邮箱地址');
         return;
       }
       
       if (!this.isEmailValid) {
         alert('请填写有效的邮箱地址');
         return;
       }
       
       this.isSendingEmail = true;
       this.emailSendRetryCount = 0;
       
       try {
         logger.log('📧 开始发送邮箱验证码到:', this.username);
         logger.log('🔐 当前图形验证码:', this.captchaCode);
         logger.log('🆔 当前验证码ID:', this.captchaId);
         
         const emailData = {
           email: this.username,
           toEmail: this.username,
           code: this.captchaCode,
           captcha: this.captchaCode,
           captchaCode: this.captchaCode,
           uuid: this.captchaId,
           captchaId: this.captchaId,
           captchaUuid: this.captchaId
         };
         
         logger.log('📧 发送请求数据:', emailData);
         logger.log('📧 重点检查: toEmail =', emailData.toEmail);
         
         const response = await userApi.sendEmailCode(emailData, (retryCount) => {
           this.emailSendRetryCount = retryCount;
         });
         
         logger.log('📧 邮箱验证码API响应:', response);
         
         if (response && (response.success || response.code === 200 || response.status === 'success' || response.data)) {
           logger.log('邮箱验证码发送成功');
           alert('验证码已发送到您的邮箱，请查收');
         } else {
           logger.warn('⚠️ 邮箱验证码发送响应异常:', response);
           alert(response.message || response.msg || '发送验证码失败，请稍后重试');
         }
         
       } catch (error) {
         logger.error('❌ 邮箱验证码发送失败:', error);
         
         if (error.response && error.response.status === 404) {
           alert('邮箱验证码接口不存在，请联系管理员');
         } else if (error.response && error.response.status === 400) {
           alert('请求参数有误，请重试');
         } else if (error.response && error.response.status === 500) {
           alert('服务器错误，请稍后重试');
         } else {
           alert('发送验证码失败，请稍后重试');
         }
       } finally {
         this.isSendingEmail = false;
       }
     },
         // 新增：图片加载成功处理
    onImageLoad() {
      logger.log('✅ 验证码图片加载成功');
    },
    // 新增：图片加载失败处理
    onImageError(event) {
      logger.error('❌ 验证码图片加载失败:', event);
      logger.error('❌ 图片src长度:', event.target.src.length);
      logger.error('❌ 图片src前100字符:', event.target.src.substring(0, 100));
      
      // 提供调试建议
      logger.log('🔧 调试建议:');
      logger.log('1. 检查后端返回的数据格式是否正确');
      logger.log('2. 确认图片格式是否为PNG或其他支持的格式');
    },
    

  },
  beforeUnmount() {
    logger.log('🧹 组件销毁前清理');
  },
  mounted() {
    logger.log('🚀 登录页面已加载');
    logger.log('🔍 初始登录模式:', this.loginMode);

    // 组件挂载后检查token状态
    this.checkTokenStatus();
    
    // 检查是否有登录提示（刚注册的用户）
    let loginHint;
    try {
      loginHint = localStorage.getItem('loginHint');
    } catch (error) {
      logger.warn('⚠️ localStorage访问失败:', error);
      loginHint = null;
    }
    if (loginHint) {
      try {
        const hint = JSON.parse(loginHint);
        if (hint.justRegistered && hint.email) {
          this.username = hint.email;
          this.loginMode = 'email'; // 自动切换到邮箱登录
          logger.log('🆕 检测到刚注册的用户，已自动填充邮箱并切换到邮箱登录模式');
          try {
          localStorage.removeItem('loginHint');
        } catch (error) {
          logger.warn('⚠️ localStorage清理失败:', error);
        }
        }
      } catch (error) {
        logger.error('解析登录提示失败:', error);
      }
    } else {
      // 检查是否有记住的用户信息
      let rememberedUser;
      try {
        rememberedUser = localStorage.getItem('userInfo');
      } catch (error) {
        logger.warn('⚠️ localStorage访问失败:', error);
        rememberedUser = null;
      }
      if (rememberedUser) {
        try {
          const userInfo = JSON.parse(rememberedUser);
          this.username = userInfo.email || userInfo.account || '';
          logger.log('💭 检测到记住的用户信息，已自动填充');
        } catch (error) {
          logger.error('解析记住的用户信息失败:', error);
        }
      }
    }
  }
};
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-container {
  width: 100%;
  max-width: 1200px;
  padding: 20px;
  display: flex;
  justify-content: center;
}

.login-box {
  width: 100%;
  max-width: 420px;
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  padding: 40px 30px;
}

.welcome-header {
  text-align: center;
  margin-bottom: 30px;
}

.welcome-header h1 {
  margin: 0 0 10px 0;
  font-size: 28px;
  font-weight: 600;
  color: #333;
}

.welcome-header p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.login-tabs {
  display: flex;
  background-color: #f0f0f0;
  border-radius: 12px;
  padding: 4px;
  margin-bottom: 30px;
  position: relative;
  z-index: 20;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px 8px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  transition: all 0.3s ease;
  user-select: none;
  position: relative;
  z-index: 10;
  pointer-events: auto;
}

.tab-item.active {
  background-color: #4CAF50;
  color: white;
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.tab-item:hover:not(.active) {
  background-color: #e0e0e0;
}

.tab-item:active {
  transform: scale(0.98);
}

.login-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-group.has-error .form-control {
  border-color: #f44336;
  box-shadow: 0 0 0 2px rgba(244, 67, 54, 0.1);
}

.error-message {
  color: #f44336;
  font-size: 12px;
  margin-top: 5px;
}

.hint-message {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}

.password-input-container {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  user-select: none;
  font-size: 18px;
}



.loading-spinner {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.form-control {
  width: 100%;
  padding: 14px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  font-size: 16px;
  background-color: #fafafa;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.form-control:focus {
  outline: none;
  border-color: #4CAF50;
  background-color: white;
  box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.1);
}

.verification-group {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 15px;
}

.verification-control {
  flex: 1;
}

.verification-btn {
  padding: 14px 20px;
  border: none;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #4CAF50;
  color: white;
  white-space: nowrap;
  min-width: 120px;
}

.verification-btn:hover:not(:disabled) {
  background-color: #43A047;
  transform: translateY(-1px);
}

.verification-btn:disabled {
  background-color: #bbb;
  cursor: not-allowed;
  color: #666;
}

.button-group {
  margin-bottom: 20px;
  position: relative;
  z-index: 50;
}

.login-btn {
  padding: 16px 0;
  width: 100%;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
  position: relative;
  z-index: 100;
  pointer-events: auto;
}

.login-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(76, 175, 80, 0.4);
}

.login-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.divider {
  position: relative;
  text-align: center;
  margin: 30px 0 20px 0;
}

.divider::before,
.divider::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 35%;
  height: 1px;
  background-color: #e0e0e0;
}

.divider::before {
  left: 0;
}

.divider::after {
  right: 0;
}

.divider span {
  display: inline-block;
  padding: 0 15px;
  background-color: white;
  color: #999;
  font-size: 14px;
}

.login-options {
  display: flex;
  gap: 15px;
  justify-content: center;
  position: relative;
  z-index: 150;
}

.guest-login-btn {
  padding: 12px 30px;
  border: 2px solid #FF9800;
  border-radius: 12px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  background-color: transparent;
  color: #FF9800;
}

.guest-login-btn:hover {
  background-color: #FF9800;
  color: white;
  transform: translateY(-1px);
}



/* 新增样式 */
.captcha-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.captcha-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 400px;
  max-height: 90%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.captcha-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f0f0f0;
  border-bottom: 1px solid #e0e0e0;
}

.captcha-header h3 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.close-btn {
  font-size: 24px;
  color: #666;
  cursor: pointer;
  transition: color 0.3s;
}

.close-btn:hover {
  color: #333;
}

.captcha-content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background-color: #f9f9f9;
}

.captcha-image-container {
  width: 100%;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-bottom: 15px;
  overflow: hidden;
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.captcha-loading {
  font-size: 18px;
  color: #666;
}

.captcha-input-group {
  width: 100%;
  max-width: 300px;
  position: relative;
}

.captcha-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
  padding-right: 40px; /* 为按钮留出空间 */
}

.captcha-input:focus {
  border-color: #4CAF50;
  box-shadow: 0 0 5px rgba(76, 175, 80, 0.5);
}

.captcha-footer {
  display: flex;
  justify-content: space-between;
  padding: 15px 20px;
  background-color: #f0f0f0;
  border-top: 1px solid #e0e0e0;
}

.captcha-refresh-btn {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
  background-color: #2196F3;
  color: white;
}

.captcha-refresh-btn:hover {
  background-color: #1976D2;
}

.captcha-confirm-btn {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
  background-color: #4CAF50;
  color: white;
}

.captcha-confirm-btn:hover {
  background-color: #43A047;
}

.captcha-refresh-btn,
.captcha-confirm-btn {
  white-space: nowrap;
}

.refresh-icon {
  margin-right: 5px;
}

.email-sending-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.email-sending-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 350px;
  max-height: 90%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  text-align: center;
}

.email-sending-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-spinner-large {
  width: 60px;
  height: 60px;
  border: 6px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
}

.retry-info {
  color: #f44336;
  font-size: 12px;
  margin-top: 10px;
}


</style> 